package cn.easybuy.service.proudct;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.easybuy.dao.product.ProductCategoryDao;
import cn.easybuy.dao.product.ProductCategoryDaoImpl;
import cn.easybuy.entity.ProductCategory;
import cn.easybuy.utils.DataSourceUtil;
import cn.easybuy.utils.ProductCategoryVo;

public class ProductCategoryServiceImpl implements ProductCategoryService {
	
	private Connection connection;
	private ProductCategoryDao pcDao;
	private	PreparedStatement pstmt;
	private ResultSet rs;
	
	@Override
	public List<ProductCategory> queryAllProductCategory(String parentId) {
		List<ProductCategory> pcList = new ArrayList<ProductCategory>();

		try {
			connection = DataSourceUtil.openConnection();
			pcDao = new ProductCategoryDaoImpl(connection);
			if (parentId == null || parentId.equals("")) {
				parentId = "0";
			}
			pcList = pcDao.queryAllProductCategory(parentId);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DataSourceUtil.closeConnection(connection);
		}
		return pcList;
	}

	@Override
	public List<ProductCategoryVo> queryAllProductCategory() {
		
		//查询一级分类的列表
		List<ProductCategoryVo> pc1VoList = new ArrayList<ProductCategoryVo>();
		//查询出所有的一级分类
		List<ProductCategory> pcList = queryAllProductCategory(null);
		
		//查询二级分类
		for (ProductCategory productCategory1 : pcList) {
			ProductCategoryVo pc1Vo = new ProductCategoryVo();
			pc1Vo.setProductCategory(productCategory1);
			
			//查询二级分类的Vo列表
			List<ProductCategoryVo> pc2VoList = new ArrayList<ProductCategoryVo>();
			//查询二级分类
			List<ProductCategory> pc2List = queryAllProductCategory(productCategory1.getId().toString());
			for (ProductCategory productCategory2 : pc2List) {
				ProductCategoryVo pc2Vo = new ProductCategoryVo();
				pc2Vo.setProductCategory(productCategory2);
				
				//查询三级分类的Vo列表
				List<ProductCategoryVo> pc3VoList = new ArrayList<ProductCategoryVo>();
				//查询三级分类
				List<ProductCategory> pc3List = queryAllProductCategory(productCategory2.getId().toString());
				for (ProductCategory productCategory3 : pc3List) {
					ProductCategoryVo pc3Vo = new ProductCategoryVo();
					pc3Vo.setProductCategory(productCategory3);
					pc3VoList.add(pc3Vo);
				}
				pc2Vo.setProductCategoryVoList(pc3VoList);
				pc2VoList.add(pc2Vo);
			}
			pc1Vo.setProductCategoryVoList(pc2VoList);
			pc1VoList.add(pc1Vo);
		}
		return pc1VoList;
	}
}
